jQuery(function (){
	var ids = []
		,loadedCounter = 0
		,partLoaded     = undefined
		;
	
	// hide content first
	jQuery('#dppositions').hide();
	jQuery('#dppositions_a_loading').show();
	
	// display content when done
	partLoaded = function (){
		loadedCounter++;
		if( loadedCounter > 1 ){
			jQuery('#dppositions_a_loading').hide();
			jQuery('#dppositions').show();
		}
	};
	
	// create an array of positions
	jQuery('div.dpposition_a_position').each(function (i, el){
		var mres = this.id.match(/(\d+)$/);
		if( mres[1] ){
			ids.push(parseInt(mres[1]));
		}
	});
	
	// bind delete button
	jQuery('div.dpposition_a_position div.dpposition_a_delete').bind('click', function ( e ){
		var mres = jQuery(this).parent().get(0).id.match(/(\d+)$/)
			,name = jQuery(this).parent().find("div.dpposition_a_position_name").text();
		if( mres[1] ){
			jQuery(this).parent().addClass("dpposition_a_deleting");
			if( confirm("Poista paikkatieto "+name+"?") ){
				window.location = dppositionParams.deleteUrl+mres[1];
			}
			jQuery(this).parent().removeClass("dpposition_a_deleting");
		}
		e.preventDefault();
	});
	
	// get all positions and aliases (might have a empty array)
	//jQuery.ajax({
	//	url: "index2.php",
	//	type: "POST",
	//	dataType: "json",
	//	data: {
	//		option:  'com_dpposition',
	//		task:    'getpositionaliases',
	//		ids:      ids.toString()
	//	},
	//	success: function ( json ){
	//		if( json.status == 'ok' ){
	//			for( i in json.positions ){
	//				(new PositionAliases(json.positions[i].dpposition_id
	//					, json.positions[i].dpposition_name
	//					, json.positions[i].aliases));
	//			}
	//			partLoaded();
	//		}else if( json.status == 'error' ){
	//			alert(json.error);
	//		}
	//	}
	//});
	partLoaded();
	
	// get all positions and tags (might have a empty array)
	jQuery.ajax({
		url: "index2.php",
		type: "POST",
		dataType: "json",
		data: {
			option:  'com_dpposition',
			task:    'getpositiontags',
			ids:      ids.toString()
		},
		success: function ( json ){
			if( json.status == 'ok' ){
				for( i in json.positions ){
					(new PositionTags(json.positions[i].dpposition_id
						, json.positions[i].dpposition_name
						, json.positions[i].tags));
				}
				partLoaded();
			}else if( json.status == 'error' ){
				alert(json.error);
			}
		}
	});
	
	// bind position edit handlers
	jQuery('div.dpposition_a_position_name').bind('click', function ( e ){
		var mres = jQuery(this).parent().get(0).id.match(/(\d+)$/);
		if( mres[1] ){
			(new Position(parseInt(mres[1]), jQuery(this).html()));
		}
		e.preventDefault();
	});
});